package com.fzs.sshd.cli.server.channel;

import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.common.channel.Channel;
import org.apache.sshd.common.channel.throttle.ChannelStreamWriter;
import org.apache.sshd.common.channel.throttle.ChannelStreamWriterResolver;
import org.apache.sshd.common.channel.throttle.DefaultChannelStreamWriter;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.util.buffer.Buffer;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class ADBChannelStreamWriterResolver implements ChannelStreamWriterResolver {
    @Override
    public ChannelStreamWriter resolveChannelStreamWriter(Channel channel, byte b) {

        return new DefaultChannelStreamWriter(channel){
            @Override
            public IoWriteFuture writeData(Buffer buffer) throws IOException {
                int len = buffer.available();      // 可用字节数
                int pos = buffer.rpos();           // 读取指针当前位置
                byte[] data = new byte[len];
                System.arraycopy(buffer.array(), pos, data, 0, len);

                String payloadStr = new String(data, StandardCharsets.UTF_8);

                StringBuilder batchOutput = new StringBuilder();
                Pattern p = Pattern.compile("[\\p{Print}\\s]+");
                Matcher m = p.matcher(payloadStr);

                while (m.find()) {
                    String token = m.group();
                    //不打印okay消息防止刷屏
                    if ("OKAY".equals(token)){
                        continue;
                    }
                    batchOutput.append(token);
                }

                if (!batchOutput.isEmpty()){
                    log.info("服务端命令:{}", batchOutput.toString().stripTrailing());
                }

                return super.writeData(buffer);
            }

            @Override
            public boolean isOpen() {
                log.info("channel打开..");
                return super.isOpen();
            }

            @Override
            public void close() throws IOException {
                log.info("channel关闭..");
                super.close();
            }
        };
    }
}
